/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmPrintAlvara.java
 *
 * Created on 01/02/2010, 14:40:12
 */

package forms;

import classes.Estabelecimentos;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
import rad.Java.Common.DB.Database;
import rad.Java.Common.DB.Search;

/**
 *
 * @author rogerio
 */
public class frmPrintAlvara extends javax.swing.JFrame {

    /** Creates new form frmPrintAlvara */
    private Estabelecimentos listEstab;
    private Search busca;

    public frmPrintAlvara() {
        initComponents();
        listEstab = new Estabelecimentos();
        busca           = new Search();

        listEstab.fillList();
        fillComboBoxEstab();
        limpaDVG();
        try {
            pesquisar();
        } catch (SQLException ex) {
            Logger.getLogger(frmPrintAlvara.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbPrintAlvara = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        cmbEstab = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Impressão de Alvará");

        jLabel1.setText("Estabelecimento");
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tbPrintAlvara.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbPrintAlvara.setName("tbPrintAlvara"); // NOI18N
        jScrollPane1.setViewportView(tbPrintAlvara);

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/exit_32x32.png"))); // NOI18N
        btnCancelar.setToolTipText("Sair");
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/forms/resources/printer_32x32.png"))); // NOI18N
        btnImprimir.setToolTipText("Imprimir");
        btnImprimir.setName("btnImprimir"); // NOI18N
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        cmbEstab.setName("cmbEstab"); // NOI18N
        cmbEstab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbEstabActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbEstab, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(btnImprimir)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnCancelar))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbEstab, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnImprimir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-431)/2, (screenSize.height-371)/2, 431, 371);
    }// </editor-fold>//GEN-END:initComponents

    private void cmbEstabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbEstabActionPerformed
        try {
            pesquisar();
        } catch (SQLException ex) {
            Logger.getLogger(frmPrintAlvara.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_cmbEstabActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        cancelar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        try {
            viewRelatorios();
        } catch (JRException ex) {
            Logger.getLogger(frmPrintAlvara.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnImprimirActionPerformed

    private void pesquisar() throws SQLException
    {
        busca.prepare();
        String sql = "";
        
        String value = "contratos.id as cont_id, estab_name, contratos.ano as cont_ano, " +
                "tecnico.tecnico_name as tec_name, estabelecimentos.id as estab_id, tecnico.id as tec_id";

        busca.setFields(value);
        busca.setTable("contratos");
        busca.setTable("estabelecimentos", "contratos.estabelecimentos_id = estabelecimentos.id");
        busca.setTable("tecnico", "tecnico.id = contratos.tecnico_id");

        busca.setConditionalWhere("estab_name = '"+cmbEstab.getSelectedItem().toString()+"'");

        sql = busca.getSql();
        if (!busca.execute()) {
            JOptionPane.showMessageDialog(null, "Erro:"+ busca.getMessageError());
            return;
        }
        fillGridView();
    }

    private void fillGridView() throws SQLException
    {
        String[] colunas = new String[]{"Código","Estabelecimento","Ano","Técnico"};
        String[][] dados = new String[][]{{}};
        DefaultTableModel dtmEstab = new DefaultTableModel(dados, colunas);

        String contrato[] = new String[4];
        int aux = 0;
        while(busca.next())
        {
            contrato[0] = busca.getValue("cont_id").toString();
            contrato[1] = busca.getValue("estab_name").toString();
            contrato[2] = busca.getValue("cont_ano").toString();
            contrato[3] = busca.getValue("tec_name").toString();
            dtmEstab.addRow(contrato);
        }
        dtmEstab.removeRow(0);
        tbPrintAlvara.setModel(dtmEstab);
    }



    private void limpaDVG()
    {
        String[] colunas = new String[]{"Código","Estabelecimento","Ano","Técnico"};
        String[][] dados = new String[][]{{}};
        DefaultTableModel dtmEstab = new DefaultTableModel(dados, colunas);
        tbPrintAlvara.setModel(dtmEstab);
    }

    public void cancelar()
    {
        this.setVisible(false);
    }

    private void viewRelatorios() throws JRException
    {
        HashMap parametros = new HashMap();
        int  index = tbPrintAlvara.getSelectedRow();
        
        if(index < 0)
        {
            JOptionPane.showMessageDialog(null, "Selecione um Alvará!");
        }
        else
        {
            String id  = tbPrintAlvara.getValueAt(index,0).toString();
            Object put = parametros.put("TESTE", id);
            JasperPrint jasperPrint = JasperFillManager.fillReport("reports/alvara.jasper", parametros, Database.getConnection());
            JasperViewer.viewReport(jasperPrint, false);
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void fillComboBoxEstab()
    {
        for(int i = 0; i < listEstab.count(); i++)
        {
            cmbEstab.addItem(listEstab.get(i).getEstab_name());
        }
    }
    // </editor-fold>
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmPrintAlvara().setVisible(true);
            }
        });
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JComboBox cmbEstab;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbPrintAlvara;
    // End of variables declaration//GEN-END:variables

}
